<template>
  <div>
    <el-input class="search" @focus="searchResultShow = true" placeholder="请输入部门、人员"
              prefix-icon="el-icon-search" v-model="keyword" @input="searchInput"/>

    <!-- 空白时显示树-->
    <el-collapse-transition>
      <div class="search-result" v-show="searchResultShow">

        <section v-show="isShowTree">
          <TreeView ref="TreeView" v-model="selectedTreeList" isCheck :isPersonCheck="isPersonCheck" :treeData="treeData"/>
        </section>

        <section v-show="!isShowTree">
          <el-checkbox-group v-model="selectedIdsArr">

            <template v-if="!isPersonCheck">
              <div class="title-name">部门名字</div>
              <div class="area-container">
                <div v-show="!departmentList.length" class="epmty-text">未找到相关部门</div>


                <div v-for="item in departmentList" :key="item.id" class="data-item">
                  <span>{{ item.label }}</span>
                  <el-checkbox :label="item.id"><span></span></el-checkbox>
                </div>
              </div>

              <div class="gray-line"/>
            </template>

            <div class="title-name">人员名字</div>
            <div class="area-container">
              <div v-show="!resultPersonList.length" class="epmty-text">未找到相关人员</div>


              <div v-for="item in resultPersonList" :key="item.id" class="data-item">
                <span>{{ item.label }}</span>
                <el-checkbox :label="item.id"><span></span></el-checkbox>
              </div>
            </div>
          </el-checkbox-group>
        </section>
      </div>
    </el-collapse-transition>

  </div>
</template>
<script>

import { throttle } from 'throttle-debounce'
import TreeView from '../TreeView'

export default {
  props: {
    personList: { default: () => [] },
    isPersonCheck: { default: false, type: Boolean }
  },
  inject: {
    Transfer: { default: () => ({}) }
  },
  computed: {
    // 当输入框 没有值的时候显示树
    isShowTree() {
      return !this.keyword
    },
    allData() {
      return this.personList[0].children.reduce((acc, item) => {
        return acc.concat(item.children || [], [item])
      }, [])
    }
  },
  watch: {
    personList: {
      handler(nv) {
        this.treeData = nv
      },
      immediate: true
    }
  },
  components: { TreeView },
  data() {
    return {
      keyword: '', //搜索字段
      searchResultShow: true,    // 是否显示搜索结果
      departmentList: [],  // 搜索结果 部门数据
      resultPersonList: [], // 搜索结果的 人员列表
      selectedIdsArr: [],   // el-checkbox 已经选择的id数组 ( 包含人员和部门 )

      selectedTreeList: [],  // 保存的是树里 已经选中了的项目 人员与部门混合在一起 对象数组
      treeData: []   // 递归树数据
    }
  },
  methods: {
    // 获取 zTreeObj 这块比较恶心.....
    getZTreeObj() {
      return this.$refs.TreeView.$refs.VuePsTree.$refs.tree.ztreeObj
    },

    cancelCheck(id) {
      if (this.isShowTree) {
        // 找到 zTree 节点 让 zTree取消选中
        const zTreeObj = this.getZTreeObj()
        const targetNode = zTreeObj.getNodeByParam('id', id, null)
        zTreeObj.checkNode(targetNode, false)

        // 修改本地数据
        const idx = this.selectedTreeList.findIndex(x => x.id === id)
        this.selectedTreeList.splice(idx, 1)

        // 否则是 el-checkbox
      } else {
        const idx = this.selectedIdsArr.findIndex(x => x.id === id)
        this.selectedIdsArr.splice(idx, 1)
      }
    },

    // 对 zTree 进行选中操作 --在从其他页点进来的时候将会接受 ids数组 [ 101, 102 ]
    execCheck(idsArr) {
      const zTreeObj = this.getZTreeObj()
      // 不延迟的话获取不到 `targetNode` 应该是因为 zTree没有渲染完成 (没找到其他解决办法)
      setTimeout(() => {
        idsArr.forEach(id => {
          // 找到目标节点
          const targetNode = zTreeObj.getNodeByParam('id', id, null)
          // 进行选中
          zTreeObj.checkNode(targetNode, true)
          // 进行父节点展开
          zTreeObj.expandNode(targetNode.getParentNode(), true)

          // 数据还原
          this.selectedTreeList = this.allData.filter(x => idsArr.includes(x.id))
          this.Transfer.rightShift()  // 调用 Transfer/index.vue 组件内的方法, 模拟用户点击
        })

      }, 100)
    },
    searchInput: throttle(500, function (keyword) {
      this.calcDepartmentList(keyword)   // 两个计算
      this.calcPersonList(keyword)
    }),
    // 计算搜索结果的部门列表
    calcDepartmentList(str) {
      const allDepartment = this.treeData[0]?.children || []
      let resArr =allDepartment.length?allDepartment.filter(x => x.children && x.label.includes(str)):[]
      this.departmentList = resArr
    },
    // 计算搜索的人员列表
    calcPersonList(str) {
      const dePerson = this.treeData[0]?.children || []
      let resArr = []
      dePerson.length?dePerson.map(item => {
        if(item.children) {
          item.children.length?item.children.map(x => {
            if(x.label.includes(str)) {
              resArr.push(x)
            }
          }):''
        }else{
          if(item.label.includes(str)) {
            resArr.push(item)
          }
        }
      }, []):''
      this.resultPersonList = resArr
    },

    // 得到`el-checkbox`复选框的已选数据
    getSelectedCheckboxList() {
      return this.allData.filter(x => this.selectedIdsArr.includes(x.id))
    }

  }
}
</script>

<style lang="scss" scoped>
.search-result {
  background-color: #fff;
  width: 100%;
  padding: 10px 0 15px 0;

  .gray-line {
    background-color: #eee;
    height: .5px;
    margin: 15px;
  }

  .title-name {
    padding-left: 20px;
    font-size: 14px;
    color: #909399;
    line-height: 30px;
  }

  .epmty-text {
    text-align: center;
    font-size: 14px;
    color: #8f8f8f
  }

  .data-item {
    font-size: 14px;
    padding: 0 20px;
    position: relative;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    color: #606266;
    height: 34px;
    line-height: 34px;
    box-sizing: border-box;
    cursor: pointer;

    display: flex;
    align-items: center;
    justify-content: space-between;

    transition: 0.2s;

    &:hover {
      background-color: #F5F7FA;
    }
  }
}

</style>
